import { login, getInfo, outlogin } from "@/api/user"
import { getToken, setToken, removeToken } from "@/utils/auth"
const getDefaultState = () => {
  return {
    token: getToken(),
    id: "",
    role_id: "",
    name: ""
    // avatar: "",
    // introduction: ""
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_ROLE_ID: (state, role_id) => {
    state.role_id = role_id
  },
  SET_NAME: (state, name) => {
    state.name = name
  }
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar
  // },
  // SET_INTRODUCTION: (state, introduction) => {
  //   state.introduction = introduction
  // }
}

const actions = {
  // 用户登录
  login: ({ commit }, userInfo) => {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data: res } = response
          commit("SET_TOKEN", res.data.token)
          setToken(res.data.token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // 获取用户信息
  getInfo: ({ commit, state }) => {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data: res } = response
          if (!res.data) return reject("验证失败，请重新登录。")
          const { id, role_id, name } = res.data
          // if (!roles || roles.length <= 0) {
          //   reject("角色必须是非空数组！")
          // }
          commit("SET_ID", id)
          commit("SET_ROLE_ID", role_id)
          commit("SET_NAME", name)
          // commit("SET_AVATAR", avatar)
          // commit("SET_INTRODUCTION", introduction)
          resolve(res.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // 用户退出
  outlogin: ({ commit, state }) => {
    return new Promise((resolve, reject) => {
      outlogin(state.token)
        .then(() => {
          removeToken()
          commit("RESET_STATE")
          commit('tagsView/delAllView', null, {root: true})
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // 删除 token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit("RESET_STATE")
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
